import cv2 as cv
import numpy as np
def image_segmentation(img):
    mask = np.zeros(img.shape[:2], np.uint8)
    bgdModel = np.zeros((1, 65), np.float64)
    fgdModel = np.zeros((1, 65), np.float64)
    rect = (2, 2, img.shape[1]-5, img.shape[0]-5)
    # 函数的返回值是更新的 mask, bgdModel, fgdModel
    cv.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv.GC_INIT_WITH_RECT)
    mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
    img = img*mask2[:, :, np.newaxis]

    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    ret, binary = cv.threshold(gray, 20, 255, cv.THRESH_BINARY)
    binary, contours, hierarchy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    leng=len(contours)
    # hull = cv.convexHull(cnt)   #计算凸包
    for i in range(leng):
        cnt=contours[i]
        epsilon = 0.01 * cv.arcLength(cnt, True)  #计算精度
        approx = cv.approxPolyDP(cnt, epsilon, True) #计算近似多边形
        approx1 = cv.approxPolyDP(cnt, epsilon, True)  # 计算近似多边形
        print(approx.shape)
        cv.polylines(img, [approx], True, (0, 255, 0), 2)#近似多边形
    # cv.polylines(img, [approx1], True, (0, 255, 0), 2)  # 近似多边形
    cv.imshow('img', img)
    cv.waitKey()
    # cv.polylines(img, [hull], True, (0, 0, 255), 2)#凸包生成的多边形
    # print(hull.shape)
    # cv.imshow('img', img)
    # cv.waitKey()

if __name__=='__main__':
    img = cv.imread('C:/Users/DELL/Desktop/hhh/4.png')
    image_segmentation(img)


